/**
 * Exercise 3.24
 * --------------------------------------------
 * Write a function that returns the number of nodes on a circular list,
 * given a pointer to one of the nodes on the list.
 * --------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef int Item;
typedef struct node *link;

struct node {
    Item item;
    link next;
};

int count(link node);

int main(int argc, char **argv) {
    if (argc != 2) {
        printf("Usage:%s N\n", argv[0]);
        return 1;
    }
    int N = atoi(argv[1]);
    if (N <= 0) {
        printf("N大于0\n");
        return 1;
    }
    int i;

    link t = malloc(sizeof(*t));
    t->item = 1;
    t->next = t;

    link x = t;

    //在节点x之后插入t
    for (i = 2; i <= N; i++) {
        t = malloc(sizeof(*t));
        t->item = i;
        t->next = x->next;
        x->next = t;
        x = t;
    }

    assert(count(x) == N);

    return 0;
}

int count(link node){
    int count = 0;
    link curr = node;
    do{
        count++;
        curr = curr->next;
    }while(curr != node);

    return count;
}
